var board = new Array();
var score = 0;
var hasConflicted = new Array();
var userNames = new Array();

$(document).ready(function() {
	//	changeToCoder();
	//	newGame();
	init();
	var moveMusic = document.getElementById("moveMusic");
	var endMusic = document.getElementById("endMusic");
});

//初始化视图
function init() {
	for(var i = 0; i < 4; i++) {
		for(var j = 0; j < 4; j++) {
			var cell = $("#cell-" + i + "-" + j);
			cell.css("top", getPostionTop(i, j));
			cell.css("left", getPostionLeft(i, j));
		}
	}
	for(var i = 0; i < 4; i++) {
		board[i] = new Array();
		hasConflicted[i] = new Array();
		for(var j = 0; j < 4; j++) {
			board[i][j] = 0;
			hasConflicted[i][j] = false;
		}
	}
	reflushView();
	score = 0;
	$("#score").text(score);
}
//随机内容
function getRandomNumber() {
	var nums = [2, 4];
	if(noSpace(board)) {
		return false;
	}
	//随机位置
	var randX = parseInt(Math.random() * 4);
	var randY = parseInt(Math.random() * 4);

	var times = 0;

	while(times < 50) {
		if(board[randX][randY] == 0) {
			break;
		}

		randX = parseInt(Math.random() * 4);
		randY = parseInt(Math.random() * 4);
		times++;
	}

	if(times == 50) {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				if(board[i][j] == 0) {
					randX = i;
					randY = j;
				}
			}
		}
	}

	//随机一个数字
	var randomNumber = nums[parseInt(Math.random() * 2)];

	//随机位置显示
	board[randX][randY] = randomNumber;
	showNumberWithAnimation(randX, randY, randomNumber);

	return true;
}
//开始新游戏
function newGame() {
	init();
	getRandomNumber();
	getRandomNumber();

	canUnlockHonor(board);
}
//更新视图
function reflushView() {
	$(".number-cell").remove();
	for(var i = 0; i < 4; i++)
		for(var j = 0; j < 4; j++) {
			$("#container").append('<div class="number-cell" id="number-cell-' + i + '-' + j + '"></div>');
			var theNumberCell = $('#number-cell-' + i + '-' + j);
			var cellImg = $('<img id="cell-img-' + i + '-' + j + '" />');
			$(theNumberCell).append(cellImg);

			if(board[i][j] == 0) {
				theNumberCell.css('width', '0px');
				theNumberCell.css('height', '0px');
				theNumberCell.css('top', getPostionTop(i, j) + 50);
				theNumberCell.css('left', getPostionLeft(i, j) + 50);
				theNumberCell.css("font-size", "35px");

				cellImg.css('width', '0px');
				cellImg.css('height', '0px');
				cellImg.css('top', getPostionTop(i, j) + 50);
				cellImg.css('left', getPostionLeft(i, j) + 50);

			} else {
				theNumberCell.css('width', '100px');
				theNumberCell.css('height', '100px');
				theNumberCell.css('top', getPostionTop(i, j));
				theNumberCell.css('left', getPostionLeft(i, j));
				theNumberCell.css('background-color', getNumberBackgroundColor(board[i][j]));
				theNumberCell.css('color', getNumberColor(board[i][j]));

				if(!textIsAStr(getNumberText(board[i][j]))) {
					theNumberCell.css("font-size", "35px");
					theNumberCell.text(getNumberText(board[i][j]));
				} else if(getNumberText(board[i][j]).substring(0, 3) == "img") {
					$(cellImg).attr("src", getNumberText(board[i][j]));
				} else {
					theNumberCell.css("font-size", "22px");
					theNumberCell.text(getNumberText(board[i][j]));
				}

				cellImg.css('width', '100px');
				cellImg.css('height', '100px');
				cellImg.css('top', getPostionTop(i, j));
				cellImg.css('left', getPostionLeft(i, j));

			}

			hasConflicted[i][j] = false;
		}
}

//监听键盘事件
$(document).keydown(function(e) {
	switch(e.keyCode) {
		case 37:
			if(moveLeft()) {
				setTimeout(getRandomNumber, 210);
				setTimeout(isGameOver, 300);
				canUnlockHonor(board);
			}
			break;
		case 38:
			if(moveUp()) {
				setTimeout(getRandomNumber, 210);
				setTimeout(isGameOver, 300);
				canUnlockHonor(board)
			}
			break;
		case 39:
			if(moveRight()) {
				setTimeout(getRandomNumber, 210);
				setTimeout(isGameOver, 300);
				canUnlockHonor(board)
			}
			break;
		case 40:
			if(moveDown()) {
				setTimeout(getRandomNumber, 210);
				setTimeout(isGameOver, 300);
				canUnlockHonor(board)
			}
			break;
		default:
			break;
	}
});

//是否游戏结束
function isGameOver() {
	if(noSpace(board) && noMove(board)) {
		gameOver();
		endMusic.play();
	}
}
//游戏结束
function gameOver() {
	//创建一个结束的谈话框
	var gameOverDiv = $("#gameOverDiv");
	gameOverDiv.toggle();
	var scoreSpan = $("#result");
	$(scoreSpan).html(score);
}
//提交游戏者名字
function submitUserName() {
	var inp = $("#userName input");
	var username = inp.val();
	userNames.push([username, score]);
	sortScore(userNames);
	var gameOverDiv = $("#gameOverDiv");
	gameOverDiv.toggle();
	//	newGame();
}
//重试按钮
function startAnNewGame() {
	var gameOverDiv = $("#gameOverDiv");
	gameOverDiv.toggle();
	newGame();
}
//左移
function moveLeft() {
	if(!canMoveLeft(board)) {
		return false;
	}
	for(var i = 0; i < 4; i++) {
		for(var j = 1; j < 4; j++) {
			if(board[i][j] != 0) {
				for(var k = 0; k < j; k++) {
					if(board[i][k] == 0 && noBlockHorizontal(i, k, j, board)) {
						showMoveAnimation(i, j, i, k);
						board[i][k] = board[i][j];
						board[i][j] = 0;
						continue;
					} else if(board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board) && !hasConflicted[i][k]) {
						showMoveAnimation(i, j, i, k);
						board[i][k] += board[i][j];
						board[i][j] = 0;
						score += board[i][k];
						updateScore(score);

						hasConflicted[i][k] = true;
						continue;
					}
				}
			}
		}
	}
	moveMusic.play();
	setTimeout(reflushView, 200);
	return true;

}
//右移
function moveRight() {
	if(!canMoveRight(board)) {
		return false;
	}

	for(var i = 0; i < 4; i++) {
		for(var j = 2; j >= 0; j--) {
			if(board[i][j] != 0) {
				for(var k = 3; k > j; k--) {
					if(board[i][k] == 0 && noBlockHorizontal(i, j, k, board)) {
						showMoveAnimation(i, j, i, k);
						board[i][k] = board[i][j];
						board[i][j] = 0;
						continue;
					} else if(board[i][k] == board[i][j] && noBlockHorizontal(i, j, k, board) && !hasConflicted[i][k]) {
						showMoveAnimation(i, j, i, k);
						board[i][k] += board[i][j];
						board[i][j] = 0;
						score += board[i][k];
						updateScore(score);
						hasConflicted[i][k] = true;
						continue;
					}
				}
			}
		}
	}
	moveMusic.play();
	setTimeout(reflushView, 200);
	return true;
}
//上移
function moveUp() {
	if(!canMoveUp(board)) {
		return false;
	}

	for(var j = 0; j < 4; j++) {
		for(var i = 1; i < 4; i++) {
			if(board[i][j] != 0) {
				for(var k = 0; k < i; k++) {
					if(board[k][j] == 0 && noBlockVertical(j, k, i, board)) {
						showMoveAnimation(i, j, k, j);
						board[k][j] = board[i][j];
						board[i][j] = 0;
						continue;
					} else if(board[k][j] == board[i][j] && noBlockVertical(j, k, i, board) && !hasConflicted[k][j]) {
						showMoveAnimation(i, j, k, j);
						board[k][j] += board[i][j];
						board[i][j] = 0;

						score += board[k][j];
						updateScore(score);
						hasConflicted[k][j] = true;
						continue;
					}
				}
			}
		}
	}
	moveMusic.play();
	setTimeout(reflushView, 200);
	return true;
}
//下移
function moveDown() {
	if(!canMoveDown(board)) {
		return false;
	}

	for(var j = 0; j < 4; j++) {
		for(var i = 2; i >= 0; i--) {
			if(board[i][j] != 0) {
				for(var k = 3; k > i; k--) {
					if(board[k][j] == 0 && noBlockVertical(j, i, k, board)) {
						showMoveAnimation(i, j, k, j);
						board[k][j] = board[i][j];
						board[i][j] = 0;
						continue;
					} else if(board[k][j] == board[i][j] && noBlockVertical(j, i, k, board) && !hasConflicted[k][j]) {
						showMoveAnimation(i, j, k, j);
						board[k][j] += board[i][j];
						board[i][j] = 0;

						score += board[k][j];
						updateScore(score);

						hasConflicted[k][j] = true;
						continue;
					}
				}
			}
		}
	}
	moveMusic.play();
	setTimeout(reflushView, 200);
	return true;
}